/* eslint-disable prefer-destructuring */
import { defineComponent } from 'vue'
import * as api from '@/api/common'

export default defineComponent({

  methods: {
    /*
      初始化下拉列表:
      options: {
        productTypeList: [],
        ownerTypeList: []
      },
      this.initOptions([
        { name: 'productType', params: null },
        { name: 'ownerType', params: null }
      ])
    */
    initOptions(initKeys = []) {
      const selectArr = initKeys.map(
        (obj) => ({
          name: obj.name[0].toUpperCase() + obj.name.slice(1),
          params: obj.params,
          replaceFields: obj.replaceFields || []
        })
      )
      Promise.allSettled(
        selectArr.map((item) => api[`get${item.name}`](item.params))
      ).then((results) => {
        results.forEach((res, num) => {
          const options = initKeys[num]
          if (res.status === 'fulfilled') {
            if (res.value.length > 0) {
              let labelKey
              let valueKey
              if (options.replaceFields && options.replaceFields.length > 0) {
                labelKey = options.replaceFields[0]
                valueKey = options.replaceFields[1]
              } else {
                [labelKey] = Object.keys(res.value[0]).filter(key => key !== 'description')
                valueKey = labelKey
              }
              this.options[`${options.name}List`] = res.value.map(
                (data) => ({
                  label: data[labelKey],
                  value: data[valueKey]
                })
              )
            } else {
              this.options[`${options.name}List`] = []
            }
          }
          if (res.status === 'rejected') {
            this.options[`${options.name}List`] = []
            console.error(`${options.name}: ${res.reason}`)
          }
        })
      })
    }
  }
})
